<template>
    <div class="word-cloud-container">
        <h2>热门词汇分析</h2>
        <div id="wordCloud" style="width: 100%; height: 600px;"></div>
    </div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as echarts from 'echarts';
import 'echarts-wordcloud/dist/echarts-wordcloud.min.js';
import request from '@/utils/request';

const fetchData = async () => {
    try {
        const res = await request.get('/wordcloud/keywords');
        console.log('接口返回数据:', res);

        let data;
        if (res && Array.isArray(res.data)) {
            data = res.data;
        } else {
            throw new Error('数据格式不正确');
        }

        drawWordCloud(data);
    } catch (error) {
        console.error('请求失败:', error);
    }
};

const drawWordCloud = (data) => {
    const chartDom = document.getElementById('wordCloud');

    const chart = echarts.init(chartDom, null, {
        width: chartDom.clientWidth,
        height: chartDom.clientHeight,
        willReadFrequently: true
    });

    const option = {
        title: {
            text: '热门词汇',
            left: 'center'
        },
        tooltip: {},
        series: [{
            type: 'wordCloud',
            shape: 'cardioid',
            left: 'center',
            top: 'center',
            width: '100%',
            height: '100%',
            sizeRange: [12, 60],
            rotationRange: [-45, 90],
            rotationStep: 45,
            gridSize: 8,
            textStyle: {
                fontFamily: 'sans-serif',
                fontWeight: 'bold',
                color: function () {
                    return 'rgb(' + [
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160)
                    ].join(',') + ')';
                }
            },
            data: data
        }]
    };

    chart.setOption(option);
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped>
.word-cloud-container {
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
}
</style>